package com.modakai.med.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.modakai.med.cmn.listener.excel.DictRedListener;
import com.modakai.med.cmn.mapper.DictMapper;
import com.modakai.med.cmn.service.DictService;
import com.modakai.med.common.exception.MedException;
import com.modakai.med.common.result.ResultCodeEnum;
import com.modakai.med.model.cmn.Dict;
import com.modakai.med.vo.DictEeVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict>
        implements DictService {

//    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public List<Dict> findChildData(Long id) {
        // 1 封装查询条件
        List<Dict> dictList = lambdaQuery().eq(Dict::getParentId, id).list();

        // 2 遍历字典集合，判断是否存在子节点
        for (Dict dict : dictList) {
            Long dictId = dict.getId();
            if (this.hasChildren(dictId)) {
                dict.setHasChildren(true);
            }
        }

        return dictList;
    }

    @Override
    public void exportData(HttpServletResponse response) {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String filename = URLEncoder.encode("数据字典", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename=" + filename + ".xlsx");

        List<Dict> dictList = lambdaQuery().list();
        List<DictEeVo> dictEeVoList = new ArrayList<>(dictList.size());
        for (Dict dict : dictList) {
            DictEeVo dictEeVo = new DictEeVo();
            dictEeVo.setId(dict.getId());
            dictEeVo.setName(dict.getName());
            dictEeVo.setValue(dict.getValue());
            dictEeVo.setParentId(dict.getParentId());
            dictEeVo.setDictCode(dict.getDictCode());
            dictEeVoList.add(dictEeVo);
        }
        try {
            EasyExcel.write(response.getOutputStream(), DictEeVo.class).sheet("数据字典").doWrite(dictEeVoList);
        } catch (IOException e) {
            throw new MedException(ResultCodeEnum.FAIL);
        }
    }

//    @CacheEvict(value = "dict", allEntries=true)
    @Override
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictRedListener(baseMapper)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            throw new MedException(ResultCodeEnum.FAIL);
        }
    }

    @Cacheable(value = "dict", keyGenerator = "keyGenerator")
    @Override
    public String getNameByParentCodeValue(String parentCode, String value) {
        //如果value能唯一定位数据字典，parentDictCode可以传空，例如：省市区的value值能够唯一确定
        if (StringUtils.isBlank(parentCode)) {
            Dict dict = lambdaQuery().eq(Dict::getValue, value).one();
            if (dict != null) {
                return dict.getName();
            }
        } else {
            Dict parentDict = lambdaQuery().eq(Dict::getDictCode, parentCode).one();
            if (parentDict != null) {
                // 根据 父级id 和 value 去查询
                Dict dict = lambdaQuery().eq(Dict::getParentId, parentDict.getId()).eq(Dict::getValue, value).one();
                return dict.getName();
            }
        }
        return "";
    }

    @Override
    public List<Dict> findByDictCode(String dictCode) {
        Dict codeDict = this.getDictByDictCode(dictCode);
        if(null == codeDict) return null;
        return this.findChildData(codeDict.getId());
    }

    public Dict getDictByDictCode(String dictCode) {
        return lambdaQuery().eq(Dict::getDictCode, dictCode).one();
    }

    public boolean hasChildren(Long id) {
        return lambdaQuery().eq(Dict::getParentId, id).count() > 0;
    }
}
